<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column label="指数名称" align="center" prop="indexNameCn" />
      <el-table-column label="指数值" align="center" prop="indexValue" />
      <el-table-column label="变化数" align="center" prop="changeValue"/>
      <el-table-column label="涨跌" align="center" prop="riseFall">
        <template slot-scope="scope">
            <span>
              {{ scope.row.riseFall }}%
            </span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="updateTime" >
        <template slot-scope="scope">
            <span v-if="scope.row.updateTime!= null">
              {{ parseTime(scope.row.updateTime,"{y}-{m}-{d}" ) }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="导入时间" align="center" prop="importTime" >
        <template slot-scope="scope">
            <span v-if="scope.row.importTime!= null">
              {{ parseTime(scope.row.importTime,"{y}-{m}-{d}") }}
            </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleImport(scope.row)"
          >导入</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:data:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改指数数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="30%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="指数名称" prop="indexNameCn">
          <el-select
            v-model="form.indexNameCn"
            placeholder="指数名称"
            clearable
            style="width: 100%"
          >
            <el-option  key="BDI" label="BDI" value="BDI"/>
            <el-option  key="NASDAQ" label="NASDAQ" value="NASDAQ"/>
            <el-option  key="BRENT CRUDE" label="BRENT CRUDE" value="BRENT CRUDE"/>
            <el-option  key="US DOLLAR" label="US DOLLAR" value="US DOLLAR"/>
          </el-select>
        </el-form-item>
        <el-form-item label="当日数值" prop="indexValue">
          <el-input v-model="form.indexValue" placeholder="请输入当日数值" />
        </el-form-item>
        <el-form-item label="变化数" prop="changeValue">
          <el-input v-model="form.changeValue" placeholder="请输入变化数" />
        </el-form-item>
        <el-form-item label="涨跌" prop="riseFall" >
          <el-input v-model="form.riseFall" placeholder="请输入涨跌" style="width: 95%"/>%
        </el-form-item>
        <el-form-item label="更新时间" prop="updateTime">
          <el-date-picker
            v-model="form.updateTime"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="timestamp">
          </el-date-picker>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?indexId=' + upload.indexId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="detailVis" title="指数详情" :visible.sync="detailVis" width="70%" append-to-body>
      <Detail :detailObj="detailObj">
      </Detail>
    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData, addData, updateData } from "@/api/system/indexData";
import { getToken } from "@/utils/auth";
import Detail from '@/views/system/indexDetail/index.vue'

export default {
  name: "Data",
  components:{
    Detail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 指数数据表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        indexNameCn: null,
        indexNameEn: null,
        indexValue: null,
        changeValue: null,
        riseFall: null,
        importTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        indexNameCn: [
          { required: true, message: "指数名称不能为空", trigger: "blur" }

        ],
        indexValue: [
          /*{ required: true, message: "当日指数不能为空", trigger: "blur" },*/
          { pattern: /^-?([1-9]\d{1,7}|\d{1})(\.\d{1,2})?$/, message:"请输入正确数字最多两位小数，8位整数", trigger: 'blur' }
        ],
        changeValue: [
          /*{ required: true, message: "变化数不能为空", trigger: "blur" },*/
          { pattern: /^-?([1-9]\d{1,7}|\d{1})(\.\d{1,2})?$/, message:"请输入正确数字最多两位小数，8位整数", trigger: 'blur' }
        ],
        riseFall: [
          /*{ required: true, message: "涨跌不能为空", trigger: "blur" },*/
          { pattern: /^-?([1-9]\d{1,7}|\d{1})(\.\d{1,2})?$/, message:"请输入正确数字最多两位小数，8位整数", trigger: 'blur' }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        indexId:null,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/indexData/importData"
      },
      detailVis:false,
      detailObj:{}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询指数数据列表 */
    getList() {
      this.loading = true;
      listData(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        indexNameCn: null,
        indexNameEn: null,
        indexValue: null,
        changeValue: null,
        riseFall: null,
        delFlag: null,
        importTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加指数数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getData(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改指数数据";
      });
    },
    /** 导入按钮操作 */
    handleImport(row) {
      this.upload.title = row.indexNameCn+"导入";
      this.upload.indexId = row.id;
      this.upload.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function() {
        return delData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleDetail(row) {
     this.detailVis = true;
     this.detailObj.id = row.id;
      this.detailObj.indexName = row.indexNameCn;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/indexData/importTemplate?indexId='+this.upload.indexId, {
      }, `index_data_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
